package org.jeecg.tender.project.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.tender.keyword.entity.TenderSecurityKeywordManagement;
import org.jeecg.tender.keyword.service.ITenderSecurityKeywordManagementService;
import org.jeecg.tender.project.constant.NoticeConstant;
import org.jeecg.tender.project.dto.req.SendProjectNoticeReqDto;
import org.jeecg.tender.project.entity.TenderProjectNotice;
import org.jeecg.tender.project.mapper.TenderProjectNoticeMapper;
import org.jeecg.tender.project.service.ITenderProjectNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: tender_project_notice
 * @Author: jeecg-boot
 * @Date:   2025-03-10
 * @Version: V1.0
 */
@Slf4j
@Service
public class TenderProjectNoticeServiceImpl extends ServiceImpl<TenderProjectNoticeMapper, TenderProjectNotice> implements ITenderProjectNoticeService {

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private ITenderSecurityKeywordManagementService tenderSecurityKeywordManagementService;
    @Resource
    private MailProperties mailConfig;
    @Autowired
    private ISysDepartService sysDepartService;

    @Override
    @SneakyThrows
    public void sendTenderProjectNotice(List<SendProjectNoticeReqDto> listInfo) {
        if (ObjectUtils.isEmpty(listInfo)) {
            log.info("招标信息为空，不发送招标信息通知");
            return;
        }
        try {
            // 根据标签id获取所有项目信息
            Map<Long, String> projectMap = tenderSecurityKeywordManagementService.listByIds(listInfo.stream().map(SendProjectNoticeReqDto::getLabelId).collect(Collectors.toList()))
                    .stream().collect(Collectors.toMap(TenderSecurityKeywordManagement::getId, TenderSecurityKeywordManagement::getSubProject));
            listInfo.forEach(item -> item.setSubProject(projectMap.get(item.getLabelId())));

            // 给不同项目的负责人发送告警通知
            Map<String, List<SendProjectNoticeReqDto>> map = listInfo.stream().collect(Collectors.groupingBy(SendProjectNoticeReqDto::getSubProject));
            for(Map.Entry<String, List<SendProjectNoticeReqDto>> entry : map.entrySet()){
                // 查询当前项目负责人
                List<TenderProjectNotice> notices = super.lambdaQuery().eq(TenderProjectNotice::getSubProject, entry.getKey()).list();
                if (ObjectUtils.isEmpty(entry.getValue()) || ObjectUtils.isEmpty(notices)) {
                    log.info("没有项目负责人，不发送通知...subProject:{}", entry.getKey());
                    continue;
                }
                log.info("发送邮件通知");

                // 整理邮件模板 标题，发布时间，截至时间，招标网址
                String msg = entry.getValue().stream()
                        .map(item -> String.format("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td>><td>%s</td>><td>%s</td></tr>",
                                item.getTenderTitle(),
                                DateUtils.formatDate(item.getTenderDate()),
                                DateUtils.formatDate(item.getEndTime()),
                                item.getWebsiteName(),
                                item.getKeywordName(),
                                item.getAddress()
                        )).collect(Collectors.joining());
                String noticeMsg = String.format(NoticeConstant.NOTICE_TEMPLATE, msg);

                //创建SimpleMailMessage对象
                MimeMessage message = javaMailSender.createMimeMessage();

                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                // 接收人
                String emailAddress = notices.stream().map(TenderProjectNotice::getEmail).distinct().collect(Collectors.joining(SymbolConstant.COMMA));
                log.info("发送邮件，接收人：{}", emailAddress);
                helper.setTo(emailAddress.split(SymbolConstant.COMMA));
                helper.setFrom(mailConfig.getUsername());
                // 主题
                SendProjectNoticeReqDto sendProjectNoticeReqDto = entry.getValue().get(0);
                if (!ObjectUtils.isEmpty(sendProjectNoticeReqDto)) {
                    String subProject = sendProjectNoticeReqDto.getSubProject();
                    SysDepart sysDepart = sysDepartService.getById(subProject);
                    String departName = ObjectUtils.isEmpty(sysDepart) ? "" : sysDepart.getDepartName();
                    helper.setSubject("招投标信息-"+DateUtils.formatDate(sendProjectNoticeReqDto.getTenderDate())+"-安全事业部-"+departName);
                }else{
                    helper.setSubject("招投标信息");
                }
                // 消息体
                helper.setText(noticeMsg, true);
                // 发送邮件
                javaMailSender.send(message);
            }
        } catch (Exception e) {
            log.warn("发送招标信息通知失败，错误原因", e);
        }

    }

}
